from flask import Blueprint,request,make_response,jsonify,redirect
from tools.captcha.captcha import captcha
from tools.Myredis import r
import json, random, time, requests
from tools.comm import send_message
from application.models.users.user import *
from tools.Myjwt import myjwt
user_blue = Blueprint("userblue",__name__)

# @user_blue.route("/reg")
# def reg():
#     res = User.query.all()
#     print(res)
#     return '欢迎使用flask'

@user_blue.route("/getImageCode")
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route("/send",methods=['POST'])
def send():
    data = request.data
    if data:
        data = json.loads(data)
        uuid = data['uuid']
        imgcode = data['imgcode']
        mobile = data['mobile']
        value = r.get_str(uuid)
        if value:
            if imgcode.lower() == value.lower().decode():
                mcode = r.get_str(mobile)
                # if mcode:
                #     return jsonify({"code": 10012, "msg": "一分钟只能发送一次"})
                scode=random.randint(10000, 99999)
                flag = send_message(mobile, scode)
                res = r.add_str(mobile, scode)
                # 删除图片验证码
                r.del_str(uuid)
                return jsonify({"code": 200, "msg": "发送成功"})
            else:
                return jsonify({"code": 10017, "msg": "图片验证码错误"})
        else:
            return jsonify({"code": 10010, "msg": "图片验证码不存在"})


@user_blue.route("/login",methods=['POST'])
def login():
    # 获取手机号、验证码参数
    data = request.data
    if data:
        data = json.loads(data)
        # 获取两个参数
        mcode = data['mcode']
        mobile=data['mobile']
        # 根据手机号去redis中获取验证码
        code = r.get_str(mobile)
        if code:
            if int(mcode) == int(code):
                # 如果相同查询数据库user表
                u = User.query.filter_by(mobile=mobile).first()
                if u:
                    r.del_str(mobile)
                    # return jsonify({"code":402,"msg":"该用户已存在"})
                else:
                    u = User(mobile=mobile,nikename=mobile)
                    db.session.add(u)
                    db.session.commit()
                token = myjwt.jwt_encode({'data': {'userid': u.id}})
                return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": u.id})
            else:
                return jsonify({"code": 10044, "msg": "验证码错误"})
        else:
            return jsonify({"code": 1004, "msg": "没有获取到参数"})











